package com.szy.bigevent.controller;

import com.github.pagehelper.PageInfo;
import com.szy.bigevent.pojo.Category;
import com.szy.bigevent.pojo.Result;
import com.szy.bigevent.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/findAll")
    public Result<PageInfo<Category>> findAll(Integer pageSize, Integer pageNum) {

        PageInfo<Category> pageInfo = categoryService.selectAll(pageSize, pageNum);
        return Result.success(pageInfo,"查询所有分类成功");
    }

    @PostMapping("/add")
    public Result add(@RequestBody Category category) {
        int cnt = categoryService.insertSelective(category);
        if (cnt > 0) {
            return Result.success(null,"添加成功");
        }
        return Result.error("添加失败");
    }


    @DeleteMapping
    public  Result delete(Integer id) {
        if (id == null){
            return Result.error("未查询到该分类记录");
        }

        int cnt = categoryService.deleteById(Long.valueOf(id));
        if (cnt > 0) {
            return Result.success(null,"删除成功");
        }
        return Result.error("删除失败");
    }

    @PatchMapping("/update")
    public Result update(@RequestBody Category category) {
        if(category.getId() == null){
            return Result.error("文章分类更新参数不全");
        }
        int cnt = categoryService.updateByIdSelective(category);
        if (cnt > 0) {
            return Result.success(null,"更新成功");
        }
        return Result.error("更新失败");
    }

    @GetMapping("/findCategorys")
    public Result<List<Category>> findCategorysForSearch() {
        List<Category> list = categoryService.selectAll();
        return Result.success(list);
    }
}
